package db

import (
	"pmservice/graph/model"

	gonanoid "github.com/matoous/go-nanoid/v2"
	"gorm.io/gorm"
)

type Hospital struct {
	gorm.Model
	UID  string
	Name string
}

func (Hospital) TableName() string {
	return "hospital"
}

func (d *Hospital) FromGQLNew(in *model.HosNew) {
	d.Name = in.Name
}

func (d *Hospital) FromGQLEdit(in *model.HosEdit) []string {
	fields := []string{}
	if in.Name != nil {
		d.Name = *in.Name
	}

	fields = append(fields, "name")
	return fields
}

func (d *Hospital) ToGQL() *model.Hospital {
	return &model.Hospital{
		UID:  d.UID,
		Name: d.Name,
	}
}

func HospitalNew(dbs *gorm.DB, input *model.HosNew) (*Hospital, error) {
	d := Hospital{
		UID: gonanoid.Must(),
	}
	d.FromGQLNew(input)
	result := dbs.Create(&d)
	if result.Error != nil {
		return nil, result.Error
	}

	return &d, nil
}

func HospitalGet(dbs *gorm.DB, uid string) *Hospital {
	d := Hospital{}
	result := dbs.Where("uid=?", uid).Take(&d)
	if result.Error != nil {
		return nil
	}

	return &d
}

func HospitalSave(dbs *gorm.DB, uid string, input *model.HosEdit) bool {
	d := Hospital{}
	fields := d.FromGQLEdit(input)
	result := dbs
	result = result.Where("uid=?", uid).
		Select(fields).
		Updates(&d)
	if result.Error != nil || result.RowsAffected == 0 {
		return false
	}

	return true
}
